package user

import (
	"context"
	"github.com/jinzhu/copier"
	apiAuth "navi-mumbai/app/api/admin/internal/auth"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/xerr"
	"strconv"
	"strings"

	"navi-mumbai/app/api/admin/internal/svc"
	"navi-mumbai/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserInviteConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserInviteConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserInviteConfigLogic {
	return &UpdateUserInviteConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserInviteConfigLogic) UpdateUserInviteConfig(req *types.UpdateUserInviteConfigReq) (resp *types.UpdateUserInviteConfigResp, err error) {
	// verify permission level
	adminUid := ctxdata.GetUidFromCtx(l.ctx)
	level := ctxdata.GetAdminPermissionLevelFromCtx(l.ctx)
	if !l.svcCtx.Auth.VerifyPermissionLevel(l.ctx, apiAuth.AdminUpdateUserInviteConfigApi, adminUid, level) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "permission denied")
	}
	l.Logger.Infof("UpdateUserInviteConfig. req: %+v", req)
	// 校验入参
	if req.SuperiorLevel < 1 || req.ReturnRatio == "" {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "SuperiorLevel Must be greater than 1 or ReturnRatio is not nil")
	}
	// 校验往上返回级数，与设置的返率是否一致
	ratioArrys := strings.Split(req.ReturnRatio, ",")
	var arr []int = make([]int, 0)
	for _, nStr := range ratioArrys {
		if nStr == "" {
			continue
		}
		num, err := strconv.Atoi(nStr)
		if err == nil {
			arr = append(arr, num)
		}
	}
	if req.SuperiorLevel != int64(len(arr)) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "SuperiorLevel Not equal to ReturnRatio length")
	}

	var in pb.UpdateUserInviteConfigReq
	_ = copier.Copy(&in, req)
	var rsp *pb.UpdateUserInviteConfigResp
	rsp, err = l.svcCtx.UcAdminRpc.UpdateUserInviteConfig(l.ctx, &in)
	if err != nil {
		return nil, err
	}
	resp = &types.UpdateUserInviteConfigResp{RetCode: 1}
	_ = copier.Copy(resp, rsp)
	return
}
